package com.burstly.lib.network.request;

import com.burstly.lib.constants.UriConstants;
import com.burstly.lib.service.HostsProviderManager;
import com.burstly.lib.service.IHostProvider;
import com.burstly.lib.util.LoggerExt;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpPost;

public abstract class AbortableAsyncTask<T> extends SafeAsyncTask<T>
  implements IAbortableRequest
{
  private static final Object LOCK = new Object();
  private static final LoggerExt LOG = LoggerExt.getInstance();
  private static final Map<String, List<AbortableAsyncTask<?>>> RUNNING_TASKS_MAP = new HashMap();
  private static final int SLEEP_BETWEEN_REQUEST = 900000;
  protected static final String TAG = "BurstlyRequestTask";
  private volatile boolean mAborted;
  private boolean mCanBeAborted;
  private String mContentType;
  private IHostProvider mHostProvider;
  private boolean mShouldUseSecondLevelServers = true;
  private boolean mUseRequestCycle = true;
  private Thread mWaitingThread;

  public AbortableAsyncTask(String paramString1, String paramString2)
  {
    setUri(paramString1);
    setBurstlyViewId(paramString2);
    this.mCanBeAborted = true;
    initMap();
    this.mHostProvider = HostsProviderManager.getAdProvider();
    this.mContentType = "text/json; charset=utf-8";
  }

  public static void abortAllRequests(String paramString)
  {
    if (paramString == null)
      return;
    int i;
    while (true)
    {
      AbortableAsyncTask localAbortableAsyncTask;
      synchronized (LOCK)
      {
        LOG.logInfo("BurstlyRequestTask", "Aborting all running requests for {0} banner instance...", new Object[] { paramString });
        List localList = (List)RUNNING_TASKS_MAP.get(paramString);
        if (localList == null)
          break label217;
        i = 0;
        Iterator localIterator = localList.iterator();
        if (!localIterator.hasNext())
          break;
        localAbortableAsyncTask = (AbortableAsyncTask)localIterator.next();
        LOG.logDebug("BurstlyRequestTask", "Aborting {0} request...", new Object[] { localAbortableAsyncTask });
        if (localAbortableAsyncTask.isCanBeAborted())
        {
          localAbortableAsyncTask.abortRequest();
          i++;
          LOG.logInfo("BurstlyRequestTask", "Running request {0} banner instance has been aborted.", new Object[] { localAbortableAsyncTask });
          localIterator.remove();
        }
      }
      LOG.logInfo("BurstlyRequestTask", "Running request {0} banner instance could not be aborted.", new Object[] { localAbortableAsyncTask });
    }
    LoggerExt localLoggerExt = LOG;
    Object[] arrayOfObject = new Object[2];
    arrayOfObject[0] = Integer.valueOf(i);
    arrayOfObject[1] = paramString;
    localLoggerExt.logInfo("BurstlyRequestTask", "{0} running requests for {1} banner instance have been aborted.", arrayOfObject);
    while (true)
    {
      return;
      label217: LOG.logWarning("BurstlyRequestTask", "Can not cancel requests for {0} burstly banner because no requests have been made yet.", new Object[] { paramString });
    }
  }

  private String chainRequest(List<String> paramList, HttpPost paramHttpPost, boolean paramBoolean)
  {
    Object localObject1 = null;
    Iterator localIterator = paramList.iterator();
    Object localObject2 = null;
    try
    {
      while (localIterator.hasNext())
      {
        String str1 = (String)localIterator.next();
        String[] arrayOfString = str1.split("://");
        HttpHost localHttpHost;
        if ((arrayOfString.length > 1) && ("https".equalsIgnoreCase(arrayOfString[0])))
          localHttpHost = new HttpHost(arrayOfString[1], 443, "https");
        label135: 
        do
        {
          try
          {
            setHost(str1);
            while (true)
            {
              checkNetworkAvailability();
              String str2 = connect(localHttpHost, paramHttpPost);
              localObject1 = str2;
              if (localObject1 == null)
                break;
              return localObject1;
              localHttpHost = new HttpHost(str1);
              setHost(str1);
            }
          }
          catch (AbortedException localAbortedException1)
          {
          }
          LOG.logDebug("BurstlyRequestTask", localAbortedException1.getError(), new Object[0]);
          return localObject1;
          if ((localIterator.hasNext()) || (!this.mShouldUseSecondLevelServers) || (paramBoolean))
            break;
          localObject1 = chainRequest(getLevelTwoServers(), paramHttpPost, true);
        }
        while ((localObject1 != null) || (!this.mUseRequestCycle));
        sleep();
        localIterator = paramList.iterator();
        checkAborted();
        localObject2 = localHttpHost;
      }
    }
    catch (AbortedException localAbortedException2)
    {
      break label135;
    }
    return localObject1;
  }

  private void checkAborted()
  {
    if (this.mAborted)
    {
      String str = getHost();
      StringBuilder localStringBuilder = new StringBuilder().append("Request to ");
      if (str != null);
      while (true)
      {
        throw new AbortedException(str + " host has been aborted due closing of application or making it run in background. ");
        str = UriConstants.getInstance().getPrimaryHost();
      }
    }
  }

  private void checkNetworkAvailability()
  {
    if (!RequestManager.isOnline())
    {
      String str = getHost();
      StringBuilder localStringBuilder = new StringBuilder().append("Request to ");
      if (str != null);
      while (true)
      {
        throw new AbortedException(str + " can not be done due network is unavailable. Aborted.");
        str = UriConstants.getInstance().getPrimaryHost();
      }
    }
  }

  private String connect(HttpHost paramHttpHost, HttpPost paramHttpPost)
  {
    if (!isHostAlive(getHost()))
    {
      logCouldNotConnect();
      return null;
    }
    try
    {
      String str = tryToConnect(paramHttpHost, paramHttpPost);
      return str;
    }
    catch (Exception localException)
    {
      LOG.logError("BurstlyRequestTask", "tryToConnect threw unchecked exception!", new Object[0]);
      LOG.logThrowable("BurstlyRequestTask", localException);
    }
    return null;
  }

  private List<AbortableAsyncTask<?>> getRunningTasksList()
  {
    String str = getBurstlyViewId();
    Object localObject;
    if (str == null)
      localObject = null;
    do
    {
      return localObject;
      localObject = (List)RUNNING_TASKS_MAP.get(str);
    }
    while (localObject != null);
    return null;
  }

  private void initMap()
  {
    String str = getBurstlyViewId();
    if (str != null)
      synchronized (LOCK)
      {
        if ((List)RUNNING_TASKS_MAP.get(str) == null)
          RUNNING_TASKS_MAP.put(str, new ArrayList(10));
        return;
      }
    LOG.logWarning("BurstlyRequestTask", "Can not create running tasks map for burstly view with null burstlyViewID!", new Object[0]);
  }

  private boolean isHostAlive(String paramString)
  {
    return true;
  }

  private void logCouldNotConnect()
  {
    LoggerExt localLoggerExt = LOG;
    Object[] arrayOfObject = new Object[1];
    arrayOfObject[0] = getUri();
    localLoggerExt.logError("BurstlyRequestTask", "Could not connect to remote host: {0}", arrayOfObject);
    LOG.logError("BurstlyRequestTask", "Moving to next one...", new Object[0]);
  }

  private void sleep()
  {
    try
    {
      long l = getSleepBetweenRequestCycles();
      LoggerExt localLoggerExt = LOG;
      Object[] arrayOfObject = new Object[1];
      arrayOfObject[0] = Long.valueOf(l);
      localLoggerExt.logInfo("BurstlyRequestTask", "Servers are not available. Scheduling next attempt in {0} ms.", arrayOfObject);
      this.mWaitingThread = Thread.currentThread();
      Thread.sleep(l);
      return;
    }
    catch (InterruptedException localInterruptedException)
    {
      LOG.logDebug("BurstlyRequestTask", "Aborted scheduled request to server.", new Object[0]);
      return;
    }
    finally
    {
      this.mWaitingThread = null;
    }
  }

  public void abortRequest()
  {
    if (this.mCanBeAborted)
      this.mAborted = true;
    if (this.mWaitingThread != null)
      this.mWaitingThread.interrupt();
  }

  protected abstract T convertServerResponse(String paramString);

  public String getContentType()
  {
    return this.mContentType;
  }

  protected List<String> getLevelOneServers()
  {
    return this.mHostProvider.getLevelOneHosts();
  }

  protected List<String> getLevelTwoServers()
  {
    return this.mHostProvider.getLevelTwoHosts();
  }

  protected long getSleepBetweenRequestCycles()
  {
    return 900000L;
  }

  public boolean isAborted()
  {
    return this.mAborted;
  }

  protected boolean isCanBeAborted()
  {
    return this.mCanBeAborted;
  }

  public boolean isShouldUseSecondLevelServers()
  {
    return this.mShouldUseSecondLevelServers;
  }

  public boolean isUseRequestCycle()
  {
    return this.mUseRequestCycle;
  }

  protected String makeRequest()
  {
    HttpPost localHttpPost = new HttpPost(getUri());
    localHttpPost.setHeader("Content-type", this.mContentType);
    return chainRequest(getLevelOneServers(), localHttpPost, false);
  }

  protected void onPostExecute(T paramT)
  {
    super.onPostExecute(paramT);
    synchronized (LOCK)
    {
      List localList = getRunningTasksList();
      if (localList != null)
      {
        localList.remove(this);
        return;
      }
      LoggerExt localLoggerExt = LOG;
      Object[] arrayOfObject = new Object[1];
      arrayOfObject[0] = getBurstlyViewId();
      localLoggerExt.logWarning("BurstlyRequestTask", "Current asynchronous task for {0} burstly banner can not be canceled on banner destroy! It will be finished in background.", arrayOfObject);
    }
  }

  protected void onPreExecute()
  {
    synchronized (LOCK)
    {
      List localList = getRunningTasksList();
      if (localList != null)
      {
        localList.add(this);
        super.onPreExecute();
        return;
      }
      LoggerExt localLoggerExt = LOG;
      Object[] arrayOfObject = new Object[1];
      arrayOfObject[0] = getBurstlyViewId();
      localLoggerExt.logWarning("BurstlyRequestTask", "Current asynchronous task for {0} burstly banner can not be canceled on banner destroy! It will be finished in background.", arrayOfObject);
    }
  }

  protected T performInBackground()
  {
    super.performInBackground();
    String str = makeRequest();
    if (str != null)
      try
      {
        Object localObject = convertServerResponse(str);
        return localObject;
      }
      catch (Exception localException)
      {
        LOG.logError("BurstlyRequestTask", "convertServerResponse threw unchecked exception!", new Object[0]);
        LOG.logThrowable("BurstlyRequestTask", localException);
      }
    return null;
  }

  protected void setCanBeAborted(boolean paramBoolean)
  {
    this.mCanBeAborted = paramBoolean;
  }

  public void setContentType(String paramString)
  {
    this.mContentType = paramString;
  }

  public void setHostProvider(IHostProvider paramIHostProvider)
  {
    this.mHostProvider = paramIHostProvider;
  }

  public void setShouldUseSecondLevelServers(boolean paramBoolean)
  {
    this.mShouldUseSecondLevelServers = paramBoolean;
  }

  public void setUseRequestCycle(boolean paramBoolean)
  {
    this.mUseRequestCycle = paramBoolean;
  }

  public String toString()
  {
    return MessageFormat.format("Request to uri {0} to host {1} related to wtih burstly banner {2}.", new Object[] { getUri(), getHost(), getBurstlyViewId() });
  }

  protected abstract String tryToConnect(HttpHost paramHttpHost, HttpPost paramHttpPost);

  static class AbortedException extends RuntimeException
  {
    private static final long serialVersionUID = 1L;
    private final String mMessage;

    AbortedException(String paramString)
    {
      this.mMessage = paramString;
    }

    String getError()
    {
      return this.mMessage;
    }
  }
}

/* Location:           E:\android\Toy Defense 2_dex2jar.jar
 * Qualified Name:     com.burstly.lib.network.request.AbortableAsyncTask
 * JD-Core Version:    0.6.2
 */